import { defineStore, storeToRefs } from 'pinia'
import api from '@/api'
export const useConfigStore = defineStore('config', {
	state: () => (<{
		bankSwitch : boolean
	}>{
			bankSwitch: false
		}),
	actions: {
		setAppConfig() {
			return new Promise((resolve) => {
				console.log(this)
				//bankSwitch - 此开关配置只在微信生效，抖音正常显示
				// #ifdef MP-TOUTIAO
				this.bankSwitch = true
				// #endif
				// // #ifdef MP-WEIXIN
				// api({
				// 	url: `/mall/content/app-configs`,
				// 	method: 'GET',
				// }).then((res : any) => {
				// 	console.log(res)
				// 	let { bankSwitch } = res.data
				// 	// 发正式包的时候要打开-为on时表示显示，off表示隐藏
				// 	this.bankSwitch = bankSwitch.value == 'on'
				// 	resolve(true)
				// })
				// // #endif
				// #ifdef APP || MP-WEIXIN
				uniCloud
					.callFunction({
						name: 'versionUpdate'
					})
					.then((res) => {
						console.log(res)
						console.log(uni.getSystemInfoSync())
						if (res.errCode == 0) {
							// 1.通过云函数拿到各平台正在审核的版本号
							const { examine_android_version, examine_ios_version, examine_wechat_version } = res.result;
							//2.获取当前应用的版本号和机型
							const ua = uni.getSystemInfoSync().platform; //android - ios
							let appVersion = ''
							// #ifdef MP-WEIXIN
							appVersion = uni.getSystemInfoSync().appVersion; //当前app版本
							// #endif
							// #ifndef MP-WEIXIN
							appVersion = uni.getSystemInfoSync().appWgtVersion; //当前app版本
							// #endif

							// 3.比较审核的版本号和当前使用应用的版本号是否相同，相同则获取开关状态否则bankSwitch设置为true
							let status : any = ""
							// #ifdef MP-WEIXIN
							status = appVersion == examine_wechat_version
							// #endif
							// #ifndef MP-WEIXIN
							if (ua == 'android') {
								status = appVersion == examine_android_version
							}
							if (ua == 'ios') {
								status = appVersion == examine_ios_version
							}
							// #endif
							console.log('对比状态', status)
							if (status) {
								this.bankSwitch = false
							} else {
								console.log('不相等配置', res)
								this.bankSwitch = true
							}
						} else {
							this.bankSwitch = true
						}
						resolve(true)


					})

				// #endif
			})
		}
	},
	persist: {
		storage: {
			getItem: (key : string) => uni.getStorageSync(key),
			setItem: (key : string, value : string) => uni.setStorageSync(key, value)
		}
	}

})

export const useConfigStoreToRefs = () => {
	return storeToRefs(useConfigStore())
}

// 使用
//获取动态显示state
// import { useConfigStoreToRefs } from '@/store/useConfigStore'
// const { bankSwitch } = useConfigStoreToRefs()
//获取方法
// import { useConfigStore } from '@/store/useConfigStore'
// const { setAppConfig } = useConfigStore()